package com.qlm.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.qlm.entity.PrizesConfig;
import com.qlm.service.IPrizesService;
import com.qlm.tools.Common;
import com.qlm.tools.DateUtils;
import com.qlm.view.PrizesView;
import com.qlm.view.ResultMessage;

public class PrizesServiceImpl implements IPrizesService {
	private static final Logger logger = LoggerFactory.getLogger(PrizesServiceImpl.class);

	@Override
	public List<PrizesConfig> getPrizesConfig(Integer type) {
		if(Common.isNullOrEmpty(type)){
			return null;
		}
		return PrizesConfig.dao.find("select num_,rate_,type_,amount_,name_ from t_yyy_config where type=?",type);
	}

	@Override
	@Before(Tx.class)
	public ResultMessage savePrizesConfig(Integer[] level,Integer[] num,Integer[] rate,Integer[] type) {
		if(!Common.isNullOrEmpty(level) && !Common.isNullOrEmpty(num) && !Common.isNullOrEmpty(type)  && !Common.isNullOrEmpty(rate) && 
				level.length==type.length &&	level.length==rate.length && level.length==num.length && level.length>0){
			Db.update("delete from t_yyy_config");
			int len = rate.length;
			for (int i = 0; i < len; i++) {
				PrizesConfig p = new PrizesConfig();
				p.set("level_", level[i]).set("num_", num[i]).set("rate_", rate[i]).set("type_", type[i]).save();
			}
			callCache("cache/updateYYY");
			return new ResultMessage(1, "保存信息信息成功", null);		
		}
		return new ResultMessage(0, "网络连接错误", null);
	}

	@Override
	public String getPrizesRecord(String aoData) {
		//将参数转换成jsonArray类型
		JSONArray jsonarray = JSONArray.parseArray(aoData);
		JSONObject obj = (JSONObject) jsonarray.get(0);
		// 传入的查询参数
		String sSearch = obj.get("sSearch").toString();
		
		List<Object> arList = new ArrayList<Object>();
		String lgSql = "SELECT s.name_,s.create_time,s.config_name_,s.mobile,u.nick_name,u.head_pic from t_yyy_exchange s,t_user u where u.openid =s.openid  ";
		lgSql = lgSql +" order by id desc ";
		List<Record> lgList = Db.find(lgSql);
		int i = 1;
		for (Record logistics : lgList) {
			PrizesView av = new PrizesView();
			av.setSeq(i);
			av.setName(logistics.get("name_")==null?"":logistics.get("name_"));
			av.setMobile(logistics.get("mobile")==null?"":logistics.get("mobile"));
			av.setCreateTime(DateUtils.formatString(
					 logistics.get("create_time"), DateUtils.PATTEN_HMS));
			av.setConfig_name_(logistics.getStr("config_name_"));
			av.setNickName(logistics.get("nick_name"));
			av.setHead_pic(logistics.get("head_pic"));
			arList.add(av);
			i++;
		}
		// 调用datatable分页查询方法，返回json对象字符串
		return Common.dataTableSearch(aoData, arList);
	}
	
	/**
	 * 发送请求给cache更新
	 * @param type
	 */
	public static void callCache(String type){
			new Thread(new Runnable() {
				public void run() {
					String cacheUrl = PropKit.get("cacheUrl");
					String[] urlArr = cacheUrl.split(",");
					try{						
						for(int i=0;i<urlArr.length;i++){
							if(Common.isEmptyString(urlArr[i])){
								HttpKit.get(urlArr[i] + type);
								logger.info(urlArr[i]+type+"请求发送成功");
							}							
						}
					}catch(Exception e){
						logger.error(e.getMessage(), e);
					}							
				}
			}).start();
	}

	@Override
	public ResultMessage findYYYConfig(Integer type) {
		if(!Common.isNullOrEmpty(type)){
			List<PrizesConfig> list = PrizesConfig.dao.find("select * from t_yyy_config where type_=?",type);
			return new ResultMessage(1, "查询成功", list);
		}
		return new ResultMessage(0, "网络连接错误", null);
	}

	@Override
	public ResultMessage findPrizes(Integer id) {
		if(!Common.isNullOrEmpty(id)){
			try {				
				PrizesConfig p = PrizesConfig.dao.findById(id);
				return new ResultMessage(1, "查询成功", p);
			} catch (Exception e) {
				logger.error(e.getMessage());
				return new ResultMessage(1, "查询奖品信息失败", null);
			}
		}
		return new ResultMessage(0, "网络连接错误", null);
	}

	@Override
	public ResultMessage savePrizes(PrizesConfig prizes) {
		Integer type = prizes.getInt("type_");
		String amount = prizes.getStr("amount_");
		boolean flg = false;
		if(type == 2){//红包
			int m = new BigDecimal(amount).multiply(new BigDecimal(100)).intValue();
			prizes.set("amount_", m);
		}
		flg = prizes.update();
		if(flg){
			callCache("cache/updateYYY");
			return new ResultMessage(1, "奖品信息保存成功", null);
		}
		return new ResultMessage(0, "奖品信息保存失败", null);
	}

	@Override
	public ResultMessage delPrizesById(Integer id) {
		if(!Common.isNullOrEmpty(id)){
			boolean flg = PrizesConfig.dao.deleteById(id);
			if(flg){
				callCache("cache/updateYYY");
				return new ResultMessage(1, "删除奖品信息成功", null);
			}
			return new ResultMessage(0, "删除奖品信息失败", null);
		}
		return new ResultMessage(0, "网络连接错误", null);
	}

	@Override
	public ResultMessage addPrizes(PrizesConfig prizes, String jf, String hb) {
		boolean flg = false;
		if(!Common.isEmptyString(jf) && Common.isEmptyString(hb)){//红包
			int m = new BigDecimal(hb).multiply(new BigDecimal(100)).intValue();
			flg = prizes.set("amount_", m).save();
		}else if(Common.isEmptyString(jf) && !Common.isEmptyString(hb)){//积分
			flg = prizes.set("amount_", jf).save();
		}else if(!Common.isEmptyString(jf) && !Common.isEmptyString(hb)){//实物
			flg = prizes.set("amount_", 0).save();
		}else{
			return new ResultMessage(0, "网络连接错误", null);
		}
		if(flg){
			callCache("cache/updateYYY");
			return new ResultMessage(1, "奖品信息保存成功", null);
		}
		return new ResultMessage(0, "奖品信息保存失败", null);
	}

}
